package com.longe.nio.chat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.Charset;
import java.util.Iterator;

public class ChatServer {
    //定义属性
    private Selector selector;
    private ServerSocketChannel listenChannel;
    private static final int PORT = 9999;

    //构造器
    //初始化工作
    public ChatServer() {

        try {
            //得到选择器
            selector = Selector.open();
            //ServerSocketChannel
            listenChannel = ServerSocketChannel.open();
            //绑定端口
            listenChannel.socket().bind(new InetSocketAddress(PORT));
            //设置非阻塞模式
            listenChannel.configureBlocking(false);
            //将该listenChannel 注册到selector, 设定感兴趣的事件为[接收就绪事件]
            listenChannel.register(selector, SelectionKey.OP_ACCEPT);
            System.err.println("服务器启动成功......");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    //监听
    public void listen() {
        try {
            //循环处理
            while (true) {
                int count = selector.select();
                if (count < 1) { //当count > 0 的时候表示有事件要处理
                    System.err.println("没啥事情干, 等待....");
                    continue;
                }
                //遍历得到selectionKey 集合
                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                while (iterator.hasNext()) {
                    //取出selectionKey
                    SelectionKey key = iterator.next();

                    //监听到accept
                    if (key.isAcceptable()) { //接收已就绪
                        //通过key反向获取对应的通道,因为只有一个服务,所以获得的serverSocketChannel就是listenChannel
                        //ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
                        SocketChannel socketChannel = listenChannel.accept();
                        //设置非阻塞
                        socketChannel.configureBlocking(false);
                        //将该 socketChannel 注册到selector, 设定感兴趣的事件为[读就绪事件]
                        socketChannel.register(selector, SelectionKey.OP_READ);
                        //提示
                        System.err.println(socketChannel.hashCode() + " 上线 ");
                        //回复client
                        socketChannel.write(Charset.forName("UTF-8")
                                .encode("小伙子, 你已连接服务器......"));
                    }
                    if (key.isReadable()) { //可读
                        //处理读
                        readMsg(key);
                    }
                    //当前的key 删除，防止重复处理
                    iterator.remove();
                }

            }

        } catch (Exception e) {
            e.printStackTrace();

        } finally {
            //发生异常处理....
        }
    }

    //读取客户端消息
    private void readMsg(SelectionKey key) {

        SocketChannel socketChannel = null;

        try {
            //通过key反向得到SocketChannel
            socketChannel = (SocketChannel) key.channel();
            //创建buffer
            ByteBuffer buffer = ByteBuffer.allocate(1024);

            StringBuilder message = new StringBuilder();
            int read;
            while ((read = socketChannel.read(buffer)) > 0) {
                //把缓存区的数据转成字符串
                String msg = new String(buffer.array(), 0, read);
                message.append(msg);
                //复位
                buffer.clear();
            }
            if (message.toString().length() > 0) {
                //输出该消息
                System.err.println(message.toString());
                //向其它的客户端转发消息(去掉自己)
                sendMessageToOtherClients(message.toString(), socketChannel);
            }
        } catch (IOException e) {
            try {
                //模拟离线
                System.err.println(socketChannel.hashCode() + " 离线了..");
                //取消注册
                key.cancel();
                //关闭通道
                socketChannel.close();
            } catch (IOException e2) {
                e2.printStackTrace();
            }
        }
    }

    //转发消息给其它客户(通道)
    private void sendMessageToOtherClients(String message, SocketChannel self) throws IOException {

        //遍历 所有注册到selector 上的 SocketChannel,并排除 self
        for (SelectionKey key : selector.keys()) {

            //通过 key 取出对应的 SocketChannel
            Channel targetChannel = key.channel();

            //排除自己
            if (targetChannel instanceof SocketChannel && targetChannel != self) {
                //转型
                SocketChannel target = (SocketChannel) targetChannel;
                //将message 存储到buffer
                ByteBuffer buffer = ByteBuffer.wrap(message.getBytes());
                //将buffer 的数据写入通道
                target.write(buffer);
            }
        }

    }

    public static void main(String[] args) {

        //创建服务器对象
        new ChatServer().listen();
    }
}